package cn.git.future;

import java.util.concurrent.*;

/**
 * @description: 回调方法以及发生异常处理
 *  whenCompleteAsync作用为异步执行
 *  exceptionally作用为异常处理
 * @program: bank-credit-sy
 * @author: lixuchun
 * @create: 2024-08-07
 */
public class CompletableFutureDemo02 {

    static ThreadPoolExecutor executor = new ThreadPoolExecutor(
            5,
            50,
            10,
            TimeUnit.SECONDS,
            new LinkedBlockingQueue<>(100),
            Executors.defaultThreadFactory(),
            new ThreadPoolExecutor.AbortPolicy());

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        System.out.println("主线程start ......");
        // 没有返回结果，可以执行任务
        CompletableFuture.runAsync(() -> {
            System.out.println("子线程执行了：" + Thread.currentThread().getName());
            int i = 10 / 0;
        }, executor).whenCompleteAsync((res, exec) -> {
            System.out.println("whenCompleteAsync1");
            System.out.println("res = " + res);
            System.out.println("exec = " + exec);
        }).exceptionally((exec) -> {
            // 发生异常处理
            System.out.println("exec1 = " + exec);
            return null;
        });

        // 带返回结果
        CompletableFuture<Integer> integerCompletableFuture = CompletableFuture.supplyAsync(() -> {
            System.out.println("子线程2执行了：" + Thread.currentThread().getName());
            int i = 10 / 0;
            return 10;
        }, executor).whenCompleteAsync((res, exec) -> {
            System.out.println("whenCompleteAsync2");
            System.out.println("res = " + res);
            System.out.println("exec = " + exec);
        }).exceptionally((exec) -> {
            // 发生异常处理，带返回值
            System.out.println("exec2" + exec);
            return -1;
        });

        Integer integer = integerCompletableFuture.get();
        System.out.println(integer);
        System.out.println("主线程end ......");
        executor.shutdown();
    }
}
